﻿using Stardust.Common.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Stardust.Server
{
    public sealed class ServiceRouteHttpModule : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += Context_BeginRequest;
        }
        private void Context_BeginRequest(object sender, EventArgs e)
        {
            var app = sender as HttpApplication;

            if (app.Request.RawUrl.StartsWith(StardustServer.StardustRoot, StringComparison.OrdinalIgnoreCase))
            {
                //进入stardust
                var path = app.Request.RawUrl.Remove(0, StardustServer.StardustRoot.Length);
                var json = string.Empty;
                if (app.Request.ContentLength > 0)
                {
                    StreamReader sr = new StreamReader(app.Request.InputStream);
                    json = sr.ReadToEnd();
                }
                if (string.IsNullOrEmpty(path) || path == "/")
                {
                    app.Response.Write("Hello Stardust!");
                }
                else
                {
                    var actionWrapper = ActionManager.GetActionWrapper(path);
                    if (actionWrapper != null)
                    {
                        var resultObject = actionWrapper.Invoke(json);
                        SerializerHelper.SerializeToStream(resultObject, resultObject.GetType(), app.Response.OutputStream);
                    }
                    else
                    {
                        var msg = "没有找到服务:" + path;
                        app.Response.Write(msg);
                        app.Response.StatusDescription = msg;
                        app.Response.Status = msg;
                        app.Response.StatusCode = 404;

                    }
                }
                app.Response.End();
            }
        }

    }
}
